<?php
/**
 * Yotaku shop - yshop
 * Copyright (c) 2016 http://www.yotaku.cn All rights reserved.
 * Author: Creatint <creatint@163.com> <http://creatint.yotaku.cn>
 */
namespace Addons\Second;
use Common\Controller\Addon;

class SecondAddon extends Addon{
    public $info = array(
        'name'=>'Second',
        'title'=>'抢购活动',
        'description'=>'抢购活动',
        'status'=>1,
        'author'=>'Creatint',
        'version'=>'0.1'
    );

    //前台展示
    public function show(){
        $activity = $this->get_activity();
        $this->assign('activity',$activity);
        
        $this->display("show");
    }

    //活动信息创建
    public function activity($post){
        $Second = D('Addons://Second/Second');


        //是否选择活动
        if(empty($post['activity']) || !(array_sum($post['activity'])>0)){
            //未选择活动，清除已存在活动
            $Second->del(null,$post['id']);
            return $post;
        }

        $post['second_start'] = strtotime(str_replace('T',' ',$post['second_start']));
        $post['second_end'] = strtotime(str_replace('T',' ',$post['second_end']));
        //构建活动数据
        $data = array(
            'goods_id'=>$post['id'],
            'start' =>  $post['second_start'],
            'number'=>  $post['second_number'],
            'price' =>  $post['second_price'],
            'end'   =>  $post['second_end'],//strtotime(str_replace('T',' ',$post['second_end'])),
		);
        $data = array_filter($data);


        
        if($res = $Second->update($data)){
            //TODO:创建活动成功
//            dump($res);
//            echo '创建活动成功';
        }else{
            //创建活动失败
//            echo '创建活动失败';
        }
        
    }

    public function activity_form($params){
        $key = $params['key'];
        $goods_id = $params['goods_id'];
		//判断是否属于本活动
        if(1 == $key && 0 < $params['activity']){

            //获取活动数据
            $Second = D('Addons://Second/Second');
            $info = $Second->getDetail($goods_id);
            trace($info,'info');
            $this->assign('key',$key);
            $this->assign('second_info',$info);

            $this->display("form");
        }elseif(1 == $key){
            $this->display("form");
        }
    }

    //加工商品数据列表，增加活动属性，对时间进行验证
    public function activity_show($arr){
        //商品不能为空
        if(empty($arr['goodss']) || !is_array($arr['goodss'])){
            return false;
        }

        //获取活动分组
        $activity = $this->get_activity();



        //获取活动数据，与商品数据合并
        $Second = D("Addons://Second/Second");
        foreach($arr['goodss'] as $k=>&$goods){
            $info = $Second->getDetail($goods['id']);
            if(empty($info) || $info['end']<=time()
                || ($activity['current']['dif_current']>0 && $activity['group'][$activity['current']['k_current']]['start']!=$info['start'])
                || (-1==$activity['current']['k_current'] && 0<=$activity['current']['k_next'] && $activity['group'][$activity['current']['k_next']]['start']!=$info['start'])
                ){
                unset($arr['goodss'][$k]);
            } else{
                $goods['second_price'] = $info['price'];
                $goods['start_number'] = $info['start_number'];
                $goods['current_number'] = $info['number'];
                $goods['second_start'] = $info['start'];
                $goods['second_end'] = $info['end'];

            }

        }
        trace($arr['goodss'],'goods');

        //若有limit，则截取数组
        if($arr['limit']>0 && $arr['limit']<count($arr['goodss'])){
            $arr['goodss'] = array_slice($arr['goodss'], 0,$arr['limit']);
        }

        return $arr['goodss'];
    }

    //显示活动时间
    public function activity_time(){
        //获取所有活动
        $Second = D("Addons://Second/Second");
        $map = array(
            'end' => array("gt",time())
        );
        $list = $Second->where($map)->order("`start` DESC")->select();
    }

    //获取单个活动商品详情
    public function activity_info($goods_info){
        if(empty($goods_info)){
            return $goods_info;
        }
        //获取活动数据，与商品数据合并
        $Second = D("Addons://Second/Second");
        $activity_info = $Second->getDetail($goods_info['id']);


        return $activity_info;
    }

    //创建订单时检查数量
    public function activity_check($goods_id){
        if(empty($goods_id)){
            //return false;
        }
        //获取活动数据
        $Second = D("Addons://Second/Second");
        $info = $Second->getItem($goods_id);

        return $info;
    }

    //获取有哪些活动
    public function get_activity(){
        $Second = D("Addons://Second/Second");
        $group = $Second->group("start")->order("start asc")->field("start,end")->select();

        //当前活动的索引
        $k_current = -1;
        //距离当前活动的结束时间
        $dif_current = null;

        //下一个活动的索引
        $k_next = -1;
        //距离下一个活动的时间
        $dif_next = null;

        foreach($group as $k=>&$v){
            $v['dif_start'] = round(($v["start"]-time()));
            $v['dif_end'] = round(($v["end"]-time()));
            $v['current'] = false;
            $v['next'] = false;
            //距离下一个活动开始时间
            if(null == $dif_next){
                $dif_next = $v['dif_start'];
            }
            //距离当前活动结束时间
            if(null == $dif_current){
                $dif_current = $v['dif_end'];
            }

            //获取当前活动
            if($v['dif_start']<0 && $v['dif_end']>0){
                $k_current = $k;
                $dif_current = $v['dif_end'];
            }

            //获取下一个活动
            if($v['dif_start']>0 && -1==$k_next){
                $k_next = $k;
                $dif_next = $v['dif_start'];
            }
        }unset($v);unset($dif);

        $k_next>=0?($group[$k_next]['next']=true):false;
        $k_current>=0?($group[$k_current]['current'] = true):false;
        $current = array(
            'k_current'=>$k_current,
            'k_next'=>$k_next,
            'dif_current'=>$group[$k_current]['dif_end'],
            'dif_next'=>$group[$k_next]['dif_start']
        );

//        dump($group);
//        dump("当前活动的索引 ".$k_current);
//        dump("当前活动的结束时间差 ".$dif_current);
//        dump("下一个活动的索引 ".$k_next);
//        dump("下一个活动的开始时间差 ".$dif_next);

        return array('group'=>$group, 'current'=>$current);
    }


    //订单confirm 处理post数据 减少库存
    public function confirm($post){
        $config = $this->getConfig();
        //活动位是否包含本插件指定位，检查是否有商品id
        if(!check_position($config['position'], $post['activity']) || !($post['goods_id']>0)){
            return $post;
        }
 
        //获取活动数据，与商品数据合并
        $Second = D("Addons://Second/Second");
        $info = $Second->getItem($post['goods_id'],$post['activity']);
//echo '活动信息';dump($info);dump($Second->getError());
        trace($info,'活动信息'.$Second->getError());
        $post['number'] = $info?$info['number']:0;
        $post['price'] = $info?$info['price']:0;

        return $post;
    }

    public function install(){
        return true;
    }

    public function uninstall(){
        return true;
    }
}
